package com.zshan.clinic.admin.service.stock;

import com.zshan.clinic.admin.constant.Constants;
import com.zshan.clinic.admin.entity.dto.StockDrugProfileDTO;
import com.zshan.clinic.admin.entity.vo.*;
import com.zshan.clinic.admin.mapper.stock.SpecDrugProfileMapper;
import com.zshan.clinic.admin.service.config.ClinicDictService;
import com.zshan.clinic.common.constant.CommonConstant;
import com.zshan.clinic.common.constant.DictConstant;
import com.zshan.clinic.common.constant.UnitConstant;
import com.zshan.clinic.common.enums.*;
import com.zshan.clinic.common.exception.BusinessFailException;
import com.zshan.clinic.common.util.decimal.BigDecimalUtils;
import com.zshan.clinic.common.util.list.ListUtil;
import com.zshan.clinic.common.util.page.PageInfo;
import com.zshan.clinic.common.util.page.PageUtils;
import com.zshan.clinic.common.util.pinyin.PinyinUtils;
import com.zshan.clinic.common.util.string.StringUtil;
import com.zshan.clinic.common.util.validate.ApprovalNumberUtil;
import com.zshan.clinic.database.dao.StockDrugProfileMapper;
import com.zshan.clinic.database.dao.StockDrugSignatureMapper;
import com.zshan.clinic.database.dao.StockDrugUsageMapper;
import com.zshan.clinic.database.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 药品档案
 */
@Slf4j
@Service
public class DrugProfileService {

    /**
     * 药品档案表
     */
    @Autowired
    private StockDrugProfileMapper stockDrugProfileMapper;

    /**
     * 药品用量表 比如说：口服 多少g
     */
    @Autowired
    private StockDrugUsageMapper stockDrugUsageMapper;

    @Autowired
    private ClinicDictService clinicDictService;

    @Autowired
    private SpecDrugProfileMapper specDrugProfileMapper;

    @Autowired
    private StockSupplyService stockSupplyService;

    @Autowired
    private StockDrugSignatureMapper stockDrugSignatureMapper;

    /**
     * 获取医生签名
     * @param clinicId
     * @param empId
     * @param drugIdList
     * @return
     */
    public List<StockDrugSignature> getSignatureList(Long clinicId,Long empId,List<Long> drugIdList){
        if(CollectionUtils.isEmpty(drugIdList)){
            return null;
        }
        StockDrugSignatureExample example = new StockDrugSignatureExample();
        StockDrugSignatureExample.Criteria criteria = example.createCriteria();
        criteria.andClinicIdEqualTo(clinicId);
        criteria.andEmpIdEqualTo(empId);
        criteria.andDrugIdIn(drugIdList);
        criteria.andSignatureIsNotNull();
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        return stockDrugSignatureMapper.selectByExample(example);
    }

    /**
     * 维护药品签名
     * @param stockDrugSignature
     */
    @Transactional(rollbackFor = Exception.class)
    public StockDrugSignatureVo updateSignature(StockDrugSignature stockDrugSignature){
        if(StringUtil.isBlank(stockDrugSignature.getSignature())){
            throw new BusinessFailException("请先维护签名！");
        }
        StockDrugProfile stockDrugProfile = getProfileById(stockDrugSignature.getDrugId());
        if(stockDrugProfile == null){
            throw new BusinessFailException("药品不存在！");
        }
        StockDrugSignature dbStockDrugSignature = getStockDrugSignature(stockDrugSignature.getClinicId(), stockDrugSignature.getEmpId(),stockDrugSignature.getDrugId());
        if(dbStockDrugSignature == null){
            stockDrugSignature.setIsEnabled(YesOrNoEnum.YES.getValue());
            stockDrugSignature.setIsDelete(YesOrNoEnum.NO.getValue());
            stockDrugSignature.setCreateTime(new Date());
            stockDrugSignatureMapper.insertSelective(stockDrugSignature);
        }else {
            dbStockDrugSignature.setSignature(stockDrugSignature.getSignature());
            dbStockDrugSignature.setUpdateUserId(stockDrugSignature.getUpdateUserId());
            dbStockDrugSignature.setUpdateBy(stockDrugSignature.getUpdateBy());
            dbStockDrugSignature.setUpdateTime(new Date());
            stockDrugSignatureMapper.updateByPrimaryKeySelective(dbStockDrugSignature);
        }
        List<StockDrugSignatureVo> signatureList = specDrugProfileMapper.getDrugSignatureList(stockDrugSignature.getClinicId(),stockDrugSignature.getEmpId(),null,YesOrNoEnum.NO.getValue(),PageUtils.getOffset(CommonConstant.DEFAULT_1,CommonConstant.DEFAULT_1),CommonConstant.DEFAULT_1);
        if(!CollectionUtils.isEmpty(signatureList)){
            return signatureList.get(0);
        }
        return null;
    }


    public StockDrugSignature getStockDrugSignature(Long clinicId,Long empId,Long drugId){
        StockDrugSignatureExample example = new StockDrugSignatureExample();
        StockDrugSignatureExample.Criteria criteria = example.createCriteria();
        criteria.andClinicIdEqualTo(clinicId);
        criteria.andEmpIdEqualTo(empId);
        criteria.andDrugIdEqualTo(drugId);
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        List<StockDrugSignature> signatureList = stockDrugSignatureMapper.selectByExample(example);
        return CollectionUtils.isEmpty(signatureList) ? null : signatureList.get(0);
    }

    /**
     * 查询签名列表
     * @param clinicId
     * @param drugName
     * @param isSignature
     * @param pageNo
     * @param pageSize
     * @return
     */
    public PageInfo<StockDrugSignatureVo> getDrugSignatureList(Long clinicId, Long empId,String drugName,String isSignature, Integer pageNo, Integer pageSize){
        Long totalCount = specDrugProfileMapper.getDrugSignatureCount(clinicId,empId,drugName,isSignature);
        if(StringUtil.isBlank(totalCount)){
            return PageInfo.build();
        }
        List<StockDrugSignatureVo> signatureList = specDrugProfileMapper.getDrugSignatureList(clinicId,empId,drugName,isSignature,PageUtils.getOffset(pageNo,pageSize),pageSize);
        return new PageInfo<>(totalCount,signatureList);
    }

    /**
     * 查询药品的信息
     * @param clinicId
     * @param drugIdList
     * @return
     */
    public List<StockDrugProfile> getDrugProfileList(Long clinicId,List<Long> drugIdList){
        StockDrugProfileExample example = new StockDrugProfileExample();
        StockDrugProfileExample.Criteria criteria = example.createCriteria();
        criteria.andClinicIdEqualTo(clinicId);
        criteria.andDrugIdIn(drugIdList);
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        return stockDrugProfileMapper.selectByExample(example);
    }

    /**
     * 查询药品列表--模板和病历选药品用
     * @param clinicId
     * @param storageId
     * @param drugName
     * @param recoms
     * @param drugCategory
     * @return
     */
    public List<StockDrugProfileDetailVo> getDrugRxStorageList(Long clinicId, Long storageId, String drugName, String recoms, String drugCategory,List<Long> drugIdList){
        // 两个都空：直接返回空集合
        if (StringUtil.isBlank(drugName) && StringUtil.isBlank(recoms) && CollectionUtils.isEmpty(drugIdList)) {
            return Collections.emptyList();
        }
        recoms = StringUtil.normalizeRecoms(recoms);
        // 名称优先：有名称则不做全文检索
        recoms = StringUtil.isNotBlank(drugName) ? null : recoms;
        List<String> drugCategoryList = DrugCategoryEnum.getPatentList();
        if(DrugCategoryEnum.TCM.getValue().equals(drugCategory)){
            drugCategoryList = DrugCategoryEnum.getTcmList();
        }
        return specDrugProfileMapper.getDrugRxList(clinicId,storageId,drugName,drugIdList,recoms,drugCategoryList);
    }

    /**
     * 查询库存
     * @param clinicId
     * @param storageId
     * @param drugIdList
     * @return
     */
    public List<StockDrugProfileDetailVo> getDrugRxStorageList(Long clinicId, Long storageId, List<Long> drugIdList){
        return specDrugProfileMapper.getDrugRxList(clinicId,storageId,null,drugIdList,null,null);
    }


    /**
     * 查询列表
     * @param clinicId
     * @param storageId
     * @param drugName
     * @param drugCategory
     * @param pageNo
     * @param pageSize
     * @return
     */
    public PageInfo<StockDrugProfileVo> getDrugProfileList(Long clinicId, Long storageId, String drugName,String drugCategory, Integer pageNo, Integer pageSize){
        Long totalCount = specDrugProfileMapper.getDrugProfileCount(clinicId,storageId,drugName,drugCategory);
        if(StringUtil.isBlank(totalCount)){
            return PageInfo.build();
        }
        List<StockDrugProfileVo> drugList = specDrugProfileMapper.getDrugProfileList(clinicId,storageId,drugName,drugCategory,PageUtils.getOffset(pageNo,pageSize),pageSize);
        return new PageInfo<>(totalCount,drugList);
    }

    /**
     * 获取档案详情
     * @param clinicId
     * @param drugId
     * @return
     */
    public StockDrugProfileDetailVo getDrugProfileDetail(Long clinicId, Long drugId,Long storageId){
        return specDrugProfileMapper.getDrugProfileDetail(clinicId,drugId,storageId);
    }

    /**
     * 批量添加
     * @param stockDrugProfileDTO
     */
    @Transactional(rollbackFor = Exception.class)
    public void addProfileDTO(StockDrugProfileDTO stockDrugProfileDTO){
        validateProfileDTO(stockDrugProfileDTO);
        stockDrugProfileDTO.setIsDelete(YesOrNoEnum.NO.getValue());
        stockDrugProfileDTO.setIsEnabled(YesOrNoEnum.YES.getValue());
        stockDrugProfileDTO.setCreateTime(new Date());
        stockDrugProfileMapper.insertSelective(stockDrugProfileDTO);
        //批量添加用法
        addDrugDetailsBatch(
                stockDrugProfileDTO.getClinicId(),
                stockDrugProfileDTO.getDrugId(),
                stockDrugProfileDTO.getCreateUserId(),
                stockDrugProfileDTO.getCreateBy(),
                stockDrugProfileDTO.getUsageList());
    }


    /**
     * 修改档案
     * @param stockDrugProfileDTO
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateProfileDTO(StockDrugProfileDTO stockDrugProfileDTO){
        //参数校验
        validateProfileDTO(stockDrugProfileDTO);
        StockDrugProfile stockDrugProfile = getProfileById(stockDrugProfileDTO.getDrugId());
        if(stockDrugProfile == null){
            throw new BusinessFailException("档案不存在");
        }
        stockDrugProfileDTO.setUpdateTime(new Date());
        stockDrugProfileMapper.updateByPrimaryKeySelective(stockDrugProfileDTO);
        //批量添加字段明细
        updateDrugDetailsBatch(
                stockDrugProfileDTO.getClinicId(),
                stockDrugProfileDTO.getDrugId(),
                stockDrugProfileDTO.getUpdateUserId(),
                stockDrugProfileDTO.getUpdateBy(),
                stockDrugProfileDTO.getUsageList()
        );
    }

    /**
     * 批量修改
     * @param clinicId
     * @param drugId
     * @param updateUserId
     * @param updateBy
     * @param usageList
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateDrugDetailsBatch(Long clinicId, Long drugId, Long updateUserId, String updateBy, List<StockDrugUsage> usageList) {
        //先批量删除旧的
        deleteDrugDetailsBatch(drugId,updateUserId,updateBy);
        //批量添加
        addDrugDetailsBatch(clinicId,drugId,updateUserId,updateBy,usageList);
    }

    /**
     * 先删除旧的
     * @param drugId
     * @param updateUserId
     * @param updateBy
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteDrugDetailsBatch(Long drugId, Long updateUserId, String updateBy) {
        StockDrugUsageExample example = new StockDrugUsageExample();
        StockDrugUsageExample.Criteria criteria = example.createCriteria();
        criteria.andDrugIdEqualTo(drugId);
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        StockDrugUsage stockDrugUsage = new StockDrugUsage();
        stockDrugUsage.setIsDelete(YesOrNoEnum.YES.getValue());
        stockDrugUsage.setUpdateUserId(updateUserId);
        stockDrugUsage.setUpdateBy(updateBy);
        stockDrugUsage.setUpdateTime(new Date());
        stockDrugUsageMapper.updateByExampleSelective(stockDrugUsage, example);
    }


    @Transactional(rollbackFor = Exception.class)
    public void addDrugDetailsBatch(Long clinicId, Long drugId, Long createUserId, String createBy, List<StockDrugUsage> usageList) {
        if(CollectionUtils.isEmpty(usageList)){
            return;
        }
        Date createTime = new Date();
        //用法
        saveUsageList(createTime,clinicId,drugId,createUserId,createBy,usageList);
    }


    @Transactional(rollbackFor = Exception.class)
    public void saveUsageList(Date createTime, Long clinicId, Long drugId, Long createUserId, String createBy, List<StockDrugUsage> usageList) {
        for(StockDrugUsage stockDrugUsage : usageList){
            stockDrugUsage.setDrugId(drugId);
            stockDrugUsage.setClinicId(clinicId);
            stockDrugUsage.setIsEnabled(YesOrNoEnum.YES.getValue());
            stockDrugUsage.setIsDelete(YesOrNoEnum.NO.getValue());
            stockDrugUsage.setCreateUserId(createUserId);
            stockDrugUsage.setCreateBy(createBy);
            stockDrugUsage.setCreateTime(createTime);
        }
        specDrugProfileMapper.addUsageBatch(usageList);
    }


    public void validateProfileDTO(StockDrugProfileDTO drugProfile) {
        if (StringUtil.isBlank(drugProfile.getDrugCategory())) {
            throw new BusinessFailException("分类不能为空");
        }
        if(!DrugCategoryEnum.isValue(drugProfile.getDrugCategory())){
            throw new BusinessFailException("分类错误");
        }
        if (StringUtil.isBlank(drugProfile.getDrugName())) {
            throw new BusinessFailException("名称不能为空");
        }
        if (drugProfile.getDrugName().length() > Constants.DRUG_NAME_LENGTH) {
            throw new BusinessFailException("名称最多"+ Constants.DRUG_NAME_LENGTH +"个字");
        }
        drugProfile.setGenericName(StringUtil.removeAllWhitespace(drugProfile.getGenericName()));
        if (StringUtil.isBlank(drugProfile.getGenericName())) {
            throw new BusinessFailException("通用名不能为空");
        }
        if (drugProfile.getGenericName().length() > Constants.DRUG_GENERIC_LENGTH) {
            throw new BusinessFailException("通用名最多"+ Constants.DRUG_GENERIC_LENGTH +"个字");
        }
        drugProfile.setDrugPinyin(PinyinUtils.getFirstLetters(drugProfile.getDrugName()));
        if(drugProfile.getMfrId() != null){
            StockMfr stockMfr = stockSupplyService.getStockMfrById(drugProfile.getMfrId());
            if (stockMfr == null) {
                throw new BusinessFailException("生产厂家不存在");
            }
        }
        if(StringUtil.isNotBlank(drugProfile.getConflicts())){
            List<String> conflictList = ListUtil.strToStrList(drugProfile.getConflicts());
            if(conflictList.size() > Constants.DRUG_CONFLICT_SIZE){
                throw new BusinessFailException("最多添加"+Constants.DRUG_CONFLICT_LENGTH+"个冲突！");
            }
            for(String conflict : conflictList){
                if(conflict.length() > Constants.DRUG_CONFLICT_LENGTH){
                    throw new BusinessFailException("单个冲突最多"+Constants.DRUG_CONFLICT_LENGTH+"个字！");
                }
            }
        }
        if(StringUtil.isNotBlank(drugProfile.getRecoms())){
            List<String> recomList = ListUtil.strToStrList(drugProfile.getRecoms());
            if(recomList.size() > Constants.DRUG_CONFLICT_SIZE){
                throw new BusinessFailException("最多添加"+Constants.DRUG_CONFLICT_LENGTH+"个推荐！");
            }
            for(String recom : recomList){
                if(recom.length() > Constants.DRUG_CONFLICT_LENGTH){
                    throw new BusinessFailException("单个推荐最多"+Constants.DRUG_CONFLICT_LENGTH+"个字！");
                }
            }
        }
        if(StringUtil.isNotBlank(drugProfile.getInstrs())){
            List<String> instrList = ListUtil.strToStrList(drugProfile.getInstrs());
            if(instrList.size() > Constants.DRUG_CONFLICT_SIZE){
                throw new BusinessFailException("最多添加"+Constants.DRUG_CONFLICT_LENGTH+"个备注！");
            }
            for(String instr : instrList){
                if(instr.length() > Constants.DRUG_CONFLICT_LENGTH){
                    throw new BusinessFailException("单个备注最多"+Constants.DRUG_CONFLICT_LENGTH+"个字！");
                }
            }
        }
        if(StringUtil.isNotBlank(drugProfile.getDosageForm())){
            if(!DosageFormEnum.isValue(drugProfile.getDosageForm())){
                throw new BusinessFailException("药品剂型错误");
            }
        }
        if(DrugCategoryEnum.PATENT_MEDICINE.getValue().equals(drugProfile.getDrugCategory())){
            drugProfile.setApprovalNumber(StringUtil.removeAllWhitespace(drugProfile.getApprovalNumber()));
            if(StringUtil.isNotBlank(drugProfile.getApprovalNumber())){
//                if(!ApprovalNumberUtil.isValidApprovalNumber(drugProfile.getApprovalNumber())){
//                    throw new BusinessFailException("批准文号格式错误！");
//                }
            }
            if (StringUtil.isNotBlank(drugProfile.getDrugIngr())) {
                List<String> drugIngrList = ListUtil.strToStrList(drugProfile.getDrugIngr());
                List<DictSysItemVo> itemList = clinicDictService.getDictItemList(DictConstant.DRUG_INGR,drugIngrList);
                if(CollectionUtils.isEmpty(itemList) || drugIngrList.size() != itemList.size()){
                    throw new BusinessFailException("药品成分错误");
                }
                drugProfile.setDrugIngrName(itemList.stream()
                        .map(DictSysItemVo::getItemName)
                        .filter(Objects::nonNull)
                        .collect(Collectors.joining(",")));
            }
            if (drugProfile.getDrugDosage() == null || drugProfile.getDrugDosage() <= CommonConstant.DEFAULT_0) {
                throw new BusinessFailException("剂量必须大于" + CommonConstant.DEFAULT_0);
            }
            DictUnitVo dictUnitVo = clinicDictService.getUnitValue(UnitTypeEnum.DOSAGE.getValue(), drugProfile.getDrugDosageUnit());
            if(dictUnitVo == null){
                throw new BusinessFailException("剂量单位错误");
            }
            drugProfile.setDrugDosageUnitText(dictUnitVo.getUnitText());
            if (drugProfile.getMinPackQty() == null || drugProfile.getMinPackQty() <= CommonConstant.DEFAULT_0) {
                throw new BusinessFailException("最小包装数不能为空");
            }
            if(drugProfile.getPrice() == null || drugProfile.getPrice() <= CommonConstant.DEFAULT_0){
                throw new BusinessFailException("售价必须大于"+CommonConstant.DEFAULT_0);
            }
            if (StringUtil.isBlank(drugProfile.getIsSplit())) {
                throw new BusinessFailException("是否允许拆零销售不能为空");
            }
            if(!YesOrNoEnum.isValue(drugProfile.getIsSplit())){
                throw new BusinessFailException("是否允许拆零销售错误");
            }
            if(YesOrNoEnum.YES.getValue().equals(drugProfile.getIsSplit())){
                Integer splitPrice = drugProfile.getSplitPrice();
                if(splitPrice == null || splitPrice <= CommonConstant.DEFAULT_0){
                    throw new BusinessFailException("拆零售价必须大于"+CommonConstant.DEFAULT_0);
                }
            }else {
                drugProfile.setSplitPrice(CommonConstant.DEFAULT_0);
            }
            if (StringUtil.isBlank(drugProfile.getIsMinSplit())) {
                throw new BusinessFailException("是否允许最小单位拆分不能为空");
            }
            if(!YesOrNoEnum.isValue(drugProfile.getIsMinSplit())){
                throw new BusinessFailException("是否允许最小单位拆分错误");
            }
            Integer stockWarningQty = drugProfile.getStockWarningQty();
            if(stockWarningQty == null){
                drugProfile.setStockWarningQty(CommonConstant.DEFAULT_0);
            }else {
                if(stockWarningQty <= CommonConstant.DEFAULT_0){
                    throw new BusinessFailException("预警数量必须大于"+CommonConstant.DEFAULT_0);
                }
            }
            List<StockDrugUsage> usageList = drugProfile.getUsageList();
            if(!CollectionUtils.isEmpty(usageList)){
                for(StockDrugUsage stockDrugUsage : usageList){
                    if(!clinicDictService.isUsageValue(stockDrugUsage.getUsageCode())){
                        throw new BusinessFailException("服用方式错误");
                    }
                    if(stockDrugUsage.getSingleMin() == null || BigDecimalUtils.lt(stockDrugUsage.getSingleMin(), BigDecimal.ZERO)){
                        throw new BusinessFailException("单次最小用量必须大于"+ CommonConstant.DEFAULT_0);
                    }
                    if(stockDrugUsage.getSingleMax() == null || BigDecimalUtils.lt(stockDrugUsage.getSingleMax(), BigDecimal.ZERO)){
                        throw new BusinessFailException("单次最大用量必须大于"+ CommonConstant.DEFAULT_0);
                    }
                    if(BigDecimalUtils.gt(stockDrugUsage.getSingleMin(),stockDrugUsage.getSingleMax())){
                        throw new BusinessFailException("单次最大用量必须大于最小用量");
                    }
//                    if(stockDrugUsage.getDailyMin() == null || BigDecimalUtils.lt(stockDrugUsage.getDailyMin(), BigDecimal.ZERO)){
//                        throw new BusinessFailException("单日最小用量必须大于"+ CommonConstant.DEFAULT_0);
//                    }
                    if(stockDrugUsage.getDailyMax() == null || BigDecimalUtils.lt(stockDrugUsage.getDailyMax(), BigDecimal.ZERO)){
                        throw new BusinessFailException("单日最大用量必须大于"+ CommonConstant.DEFAULT_0);
                    }
//                    if(BigDecimalUtils.gt(stockDrugUsage.getDailyMin(),stockDrugUsage.getDailyMax())){
//                        throw new BusinessFailException("单日最大用量必须大于最小用量");
//                    }
                    if(stockDrugUsage.getMinAgeYear() == null){
                        stockDrugUsage.setMinAgeYear(CommonConstant.DEFAULT_0);
                    }
                    if(stockDrugUsage.getMinAgeMonth() == null){
                        stockDrugUsage.setMinAgeMonth(CommonConstant.DEFAULT_0);
                    }
                    if(stockDrugUsage.getMaxAgeYear() == null){
                        stockDrugUsage.setMaxAgeYear(CommonConstant.DEFAULT_0);
                    }
                    if(stockDrugUsage.getMaxAgeMonth() == null){
                        stockDrugUsage.setMaxAgeMonth(CommonConstant.DEFAULT_0);
                    }
                    // 年龄统一转为月数
                    int minAgeInMonths = stockDrugUsage.getMinAgeYear() * CommonConstant.DEFAULT_12 + stockDrugUsage.getMinAgeMonth();
                    int maxAgeInMonths = stockDrugUsage.getMaxAgeYear() * CommonConstant.DEFAULT_12 + stockDrugUsage.getMaxAgeMonth();
//                    if (maxAgeInMonths == 0) {
//                        throw new BusinessFailException("最大适用年龄必须大于" + CommonConstant.DEFAULT_0);
//                    }
                    if (maxAgeInMonths > 0 &&  minAgeInMonths > 0 && maxAgeInMonths <= minAgeInMonths) {
                        throw new BusinessFailException("最大适用年龄必须大于最小适用年龄");
                    }
                }
            }
        }else if (DrugCategoryEnum.TCM.getValue().equals(drugProfile.getDrugCategory())){
            if(drugProfile.getPrice() == null || drugProfile.getPrice() <= CommonConstant.DEFAULT_0){
                throw new BusinessFailException("售价必须大于"+CommonConstant.DEFAULT_0);
            }
            //中药默认是g
            drugProfile.setDosageForm(DosageFormEnum.GRAN.getValue());
            drugProfile.setDrugDosage(CommonConstant.DEFAULT_0);
            drugProfile.setDrugDosageUnit(UnitConstant.g);
            DictUnitVo dictUnitVo = clinicDictService.getUnitValue(UnitTypeEnum.DOSAGE.getValue(), drugProfile.getDrugDosageUnit());
            if(dictUnitVo == null){
                throw new BusinessFailException("剂量单位错误");
            }
            drugProfile.setDrugDosageUnitText(dictUnitVo.getUnitText());
            drugProfile.setMinPackQty(CommonConstant.DEFAULT_1);
            drugProfile.setMinPackUnit(UnitConstant.g1);
            drugProfile.setPackUnit(UnitConstant.g1);
            drugProfile.setIsSplit(YesOrNoEnum.NO.getValue());
            drugProfile.setIsMinSplit(YesOrNoEnum.NO.getValue());
        }else if (DrugCategoryEnum.CONSUMABLE.getValue().equals(drugProfile.getDrugCategory())){
            if (drugProfile.getMinPackQty() == null || drugProfile.getMinPackQty() <= CommonConstant.DEFAULT_0) {
                throw new BusinessFailException("最小包装数不能为空");
            }
            if(drugProfile.getPrice() == null || drugProfile.getPrice() <= CommonConstant.DEFAULT_0){
                throw new BusinessFailException("售价必须大于"+CommonConstant.DEFAULT_0);
            }
            if (StringUtil.isBlank(drugProfile.getIsSplit())) {
                throw new BusinessFailException("是否允许拆零销售不能为空");
            }
            if(!YesOrNoEnum.isValue(drugProfile.getIsSplit())){
                throw new BusinessFailException("是否允许拆零销售错误");
            }
            if(YesOrNoEnum.YES.getValue().equals(drugProfile.getIsSplit())){
                Integer splitPrice = drugProfile.getSplitPrice();
                if(splitPrice == null || splitPrice <= CommonConstant.DEFAULT_0){
                    throw new BusinessFailException("拆零售价必须大于"+CommonConstant.DEFAULT_0);
                }
            }else{
                drugProfile.setSplitPrice(CommonConstant.DEFAULT_0);
            }
            //耗材默认不允许最小单位拆分
            drugProfile.setIsMinSplit(YesOrNoEnum.NO.getValue());
        }
        DictUnitVo dictMinPackUnit = clinicDictService.getUnitValue(UnitTypeEnum.DRUG.getValue(), drugProfile.getMinPackUnit());
        if(dictMinPackUnit == null){
            throw new BusinessFailException("最小包装单位错误");
        }
        drugProfile.setMinPackUnitText(dictMinPackUnit.getUnitText());
        DictUnitVo dictPackUnit = clinicDictService.getUnitValue(UnitTypeEnum.DRUG.getValue(), drugProfile.getPackUnit());
        if(dictPackUnit == null){
            throw new BusinessFailException("包装单位错误");
        }
        drugProfile.setPackUnitText(dictPackUnit.getUnitText());
    }


    /**
     * 根据 drugId 查询药品用量列表
     * @param clinicId
     * @param drugId
     * @param pageNo
     * @param pageSize
     * @return
     */
    public List<StockDrugUsage> getDrugUsageListByParams(Long clinicId, Long drugId, Integer pageNo, Integer pageSize) {
        StockDrugUsageExample example = new StockDrugUsageExample();
        StockDrugUsageExample.Criteria criteria = example.createCriteria();
        if (drugId != null) {
            criteria.andDrugIdEqualTo(drugId);
        }
        criteria.andClinicIdEqualTo(clinicId);
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        example.setOffset(PageUtils.getOffset(pageNo, pageSize));
        example.setLimit(pageSize);
        return stockDrugUsageMapper.selectByExample(example);
    }

    /**
     * 添加药品用量
     * @param usage
     */
    @Transactional(rollbackFor = Exception.class)
    public void addUsage(StockDrugUsage usage) {
        validateUsage(usage);
        usage.setIsDelete(YesOrNoEnum.NO.getValue());
        usage.setIsEnabled(YesOrNoEnum.YES.getValue());
        usage.setCreateTime(new Date());
        stockDrugUsageMapper.insertSelective(usage);
    }

    public void validateUsage(StockDrugUsage usage) {
        if (usage.getDrugId() == null) {
            throw new BusinessFailException("药品ID不能为空");
        }
    }

    /**
     * 根据ID查询药品用量
     * @param usageId
     * @return
     */
    public StockDrugUsage getUsageById(Long usageId) {
        if (usageId == null) {
            return null;
        }
        StockDrugUsage usage = stockDrugUsageMapper.selectByPrimaryKey(usageId);
        if (usage == null || YesOrNoEnum.YES.getValue().equals(usage.getIsDelete())) {
            return null;
        }
        return usage;
    }

    /**
     * 修改药品用量
     * @param usage
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateUsage(StockDrugUsage usage) {
        validateUsage(usage);
        StockDrugUsage dbUsage = getUsageById(usage.getUsageId());
        if (dbUsage == null) {
            throw new BusinessFailException("药品用量不存在");
        }
        usage.setUpdateTime(new Date());
        stockDrugUsageMapper.updateByPrimaryKeySelective(usage);
    }

    /**
     * 删除药品用量
     * @param usage
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteUsage(StockDrugUsage usage) {
        StockDrugUsage dbUsage = getUsageById(usage.getUsageId());
        if (dbUsage == null) {
            throw new BusinessFailException("药品用量不存在");
        }
        // TODO 是否需要检查关联数据
        dbUsage.setIsDelete(YesOrNoEnum.YES.getValue());
        dbUsage.setUpdateUserId(usage.getUpdateUserId());
        dbUsage.setUpdateBy(usage.getUpdateBy());
        dbUsage.setUpdateTime(new Date());
        stockDrugUsageMapper.updateByPrimaryKeySelective(dbUsage);
    }

    /**
     * 启用药品用量
     * @param usage
     */
    @Transactional(rollbackFor = Exception.class)
    public void enableUsage(StockDrugUsage usage) {
        StockDrugUsage dbUsage = getUsageById(usage.getUsageId());
        if (dbUsage == null) {
            throw new BusinessFailException("药品用量不存在");
        }
        if (YesOrNoEnum.YES.getValue().equals(dbUsage.getIsEnabled())) {
            return;
        }
        dbUsage.setIsEnabled(YesOrNoEnum.YES.getValue());
        dbUsage.setUpdateUserId(usage.getUpdateUserId());
        dbUsage.setUpdateBy(usage.getUpdateBy());
        dbUsage.setUpdateTime(new Date());
        stockDrugUsageMapper.updateByPrimaryKeySelective(dbUsage);
    }

    /**
     * 停用药品用量
     * @param usage
     */
    @Transactional(rollbackFor = Exception.class)
    public void disableUsage(StockDrugUsage usage) {
        StockDrugUsage dbUsage = getUsageById(usage.getUsageId());
        if (dbUsage == null) {
            throw new BusinessFailException("药品用量不存在");
        }
        if (YesOrNoEnum.NO.getValue().equals(dbUsage.getIsEnabled())) {
            return;
        }
        dbUsage.setIsEnabled(YesOrNoEnum.NO.getValue());
        dbUsage.setUpdateUserId(usage.getUpdateUserId());
        dbUsage.setUpdateBy(usage.getUpdateBy());
        dbUsage.setUpdateTime(new Date());
        stockDrugUsageMapper.updateByPrimaryKeySelective(dbUsage);
    }


    public List<StockDrugProfile> getDrugProfileListByParams(Long clinicId, String drugName, Integer pageNo, Integer pageSize) {
        StockDrugProfileExample example = new StockDrugProfileExample();
        StockDrugProfileExample.Criteria criteria = example.createCriteria();
        if (StringUtil.isNotBlank(drugName)) {
            criteria.andDrugNameLike("%" + drugName + "%");
        }
        criteria.andClinicIdEqualTo(clinicId);
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        example.setOffset(PageUtils.getOffset(pageNo, pageSize));
        example.setLimit(pageSize);
        return stockDrugProfileMapper.selectByExample(example);
    }

    /**
     * 添加药品档案
     * @param drugProfile
     */
    @Transactional(rollbackFor = Exception.class)
    public void addProfile(StockDrugProfile drugProfile) {
        validateProfile(drugProfile);
        drugProfile.setIsDelete(YesOrNoEnum.NO.getValue());
        drugProfile.setIsEnabled(YesOrNoEnum.YES.getValue());
        drugProfile.setCreateTime(new Date());
        stockDrugProfileMapper.insertSelective(drugProfile);
    }

    public void validateProfile(StockDrugProfile drugProfile) {

    }

    /**
     * 根据ID查询药品档案
     * @param drugId
     * @return
     */
    public StockDrugProfile getProfileById(Long drugId) {
        if (StringUtil.isBlank(drugId)) {
            return null;
        }
        StockDrugProfile drugProfile = stockDrugProfileMapper.selectByPrimaryKey(drugId);
        if (drugProfile == null || YesOrNoEnum.YES.getValue().equals(drugProfile.getIsDelete())) {
            return null;
        }
        return drugProfile;
    }

    /**
     * 修改药品档案
     * @param drugProfile
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateProfile(StockDrugProfile drugProfile) {
        validateProfile(drugProfile);
        StockDrugProfile dbDrugProfile = getProfileById(drugProfile.getDrugId());
        if (dbDrugProfile == null) {
            throw new BusinessFailException("药品不存在");
        }
        drugProfile.setUpdateTime(new Date());
        stockDrugProfileMapper.updateByPrimaryKeySelective(drugProfile);
    }

    /**
     * 删除药品档案
     * @param drugProfile
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteProfile(StockDrugProfile drugProfile) {
        StockDrugProfile dbDrugProfile = getProfileById(drugProfile.getDrugId());
        if (dbDrugProfile == null) {
            throw new BusinessFailException("药品不存在");
        }
        // TODO 检查药品是否有库存记录
        dbDrugProfile.setIsDelete(YesOrNoEnum.YES.getValue());
        dbDrugProfile.setUpdateUserId(drugProfile.getUpdateUserId());
        dbDrugProfile.setUpdateBy(drugProfile.getUpdateBy());
        dbDrugProfile.setUpdateTime(new Date());
        stockDrugProfileMapper.updateByPrimaryKeySelective(dbDrugProfile);
    }

    /**
     * 启用药品档案
     * @param drugProfile
     */
    @Transactional(rollbackFor = Exception.class)
    public void enableProfile(StockDrugProfile drugProfile) {
        StockDrugProfile dbDrugProfile = getProfileById(drugProfile.getDrugId());
        if (dbDrugProfile == null) {
            throw new BusinessFailException("药品不存在");
        }
        if (YesOrNoEnum.YES.getValue().equals(dbDrugProfile.getIsEnabled())) {
            return;
        }
        dbDrugProfile.setIsEnabled(YesOrNoEnum.YES.getValue());
        dbDrugProfile.setUpdateUserId(drugProfile.getUpdateUserId());
        dbDrugProfile.setUpdateBy(drugProfile.getUpdateBy());
        dbDrugProfile.setUpdateTime(new Date());
        stockDrugProfileMapper.updateByPrimaryKeySelective(dbDrugProfile);
    }

    /**
     * 停用药品档案
     * @param drugProfile
     */
    @Transactional(rollbackFor = Exception.class)
    public void disableProfile(StockDrugProfile drugProfile) {
        StockDrugProfile dbDrugProfile = getProfileById(drugProfile.getDrugId());
        if (dbDrugProfile == null) {
            throw new BusinessFailException("药品不存在");
        }
        if (YesOrNoEnum.NO.getValue().equals(dbDrugProfile.getIsEnabled())) {
            return;
        }
        dbDrugProfile.setIsEnabled(YesOrNoEnum.NO.getValue());
        dbDrugProfile.setUpdateUserId(drugProfile.getUpdateUserId());
        dbDrugProfile.setUpdateBy(drugProfile.getUpdateBy());
        dbDrugProfile.setUpdateTime(new Date());
        stockDrugProfileMapper.updateByPrimaryKeySelective(dbDrugProfile);
    }
    /**
     * 获取有效的查验项目
     * @param drugIdList
     * @return
     */
    public List<StockDrugProfile> getEnabledDrugProfileList(List<Long> drugIdList) {
        StockDrugProfileExample example = new StockDrugProfileExample();
        StockDrugProfileExample.Criteria criteria = example.createCriteria();
        criteria.andDrugIdIn(drugIdList);
        criteria.andIsEnabledEqualTo(YesOrNoEnum.YES.getValue());
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        return stockDrugProfileMapper.selectByExample(example);
    }

}
